package com.site.blog.my.core.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.site.blog.my.core.dao.BlogConfigMapper;
import com.site.blog.my.core.entity.BlogConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * 七牛云工具类
 */
@Component
public class QiniuUtils {


    @Autowired
    private BlogConfigMapper configMapper;

    private static String ACCESSKEY = "xxxxx-xxxx-xxxxxxx-xxxxx";
    private static String SECRETKEY = "xxxxx-xxxx-xxxxxxx-xxxxx";
    private static String BUCKET = "yangshare";

    //初始化信息
    private void init() {
        BlogConfig blogConfig = configMapper.selectByPrimaryKey("qiniu_accesskey");
        if (blogConfig != null) {
            ACCESSKEY = blogConfig.getConfigValue();
        }
        blogConfig = configMapper.selectByPrimaryKey("qiniu_secretkey");
        if (blogConfig != null) {
            SECRETKEY = blogConfig.getConfigValue();
        }
        blogConfig = configMapper.selectByPrimaryKey("qiniu_bucket");
        if (blogConfig != null) {
            BUCKET = blogConfig.getConfigValue();
        }


    }

    /**
     * @param inputStream
     * @return 七牛云hash
     */
    public String storage(InputStream inputStream) {
        //初始化
        init();
        String hash = "";
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);

        //...生成上传凭证，然后准备上传
        Auth auth = Auth.create(ACCESSKEY, SECRETKEY);
        String upToken = auth.uploadToken(BUCKET);

        try {
            Response response = uploadManager.put(inputStream, null, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            hash = putRet.key;
            /*System.out.println(putRet.key);
            System.out.println(putRet.hash);*/
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        } finally {
            return hash;
        }

    }

}
